#include <REGX52.H>
#include "Key.h"
#include "timer.h"
#include "LCD1602.h"
#include "display.h"
#include "Pin.h"

// 当前计数
unsigned int count = 0 ;
// 累计计数 ———— 数码管显示
unsigned char cumu_count = 0 ;
//
unsigned int alarming = 0;

// 当前模式
extern int CUR_MODE;

extern unsigned int threshold;

void Timer0_Init(){						// 2ms
	TMOD &= 0xF0;		//设置定时器模式
	TMOD |= 0x01;		//设置定时器模式
	TL0 = 0xCD;		//设置定时初值
	TH0 = 0xF8;		//设置定时初值
	TF0 = 0;		//清除TF0标志
	TR0 = 1;		//定时器0开始计时
	ET0 = 1;
	EA = 1;
}

void Timer1_Init(){							// 50ms
	TMOD &= 0x0F;		//设置定时器模式
	TMOD |= 0x10;		//设置定时器模式
	TL1 = 0x00;		//设置定时初值
	TH1 = 0x4C;		//设置定时初值
	TF1 = 0;		//清除TF1标志
	TR1 = 1;		//定时器1开始计时
	PT1 = 1;
	ET1 = 1;
}

void Timer2_Init(){
	T2MOD = 0;		//初始化模式寄存器
	T2CON = 0;		//初始化控制寄存器
	TL2 = 0x00;		//设置定时初值
	TH2 = 0x82;		//设置定时初值
	RCAP2L = 0x00;		//设置定时重载值
	RCAP2H = 0x82;		//设置定时重载值
	TR2 = 0;		//定时器2不开始计时
	ET2 = 1;
}



void Timer0_Rountine() interrupt 1{
	// T0计数辅助变量
	static unsigned char T0count = 0;
	TL0 = 0xCD;		//设置定时初值
	TH0 = 0xF8;		//设置定时初值
	KeyCheck();
	Buzzer = (alarming) ? ~Buzzer : Buzzer;
	LED1 = (alarming) ? 0 : 1 ;
	T0count++;
	if(T0count == 20){
		Dis_ShowNum(4,cumu_count);
		T0count = 0;
	}
}



void Timer1_Rountine() interrupt 3{
	// T1计数辅助变量
	static unsigned char T1count = 0;
	TL1 = 0x00;		//设置定时初值
	TH1 = 0x4C;		//设置定时初值
	T1count++;
	alarming = (alarming) ? (alarming-1): alarming ;
	
	// 当刚开机时，
	if(T1count == 10 && CUR_MODE == -1){
		LCD_WriteCommand(0x18);
		T1count = 0;
	}
	
	if(T1count == 20 && CUR_MODE == COUNT){
		// 计数+1
		count++;
		// 如果达到阈值，累计计数 + 1，计数清零 0
		cumu_count = (count == threshold) ? (cumu_count + 1): cumu_count ;
		alarming = (count == threshold) ? 60: alarming ;
		count = (count == threshold) ? 0 : count ;
		// T1计数清零
		T1count = 0;
		
		LCD_ShowNum(2,11,cumu_count,2);
		LCD_ShowNum(2,14,count,3);
	}
}